<?php 
class PUtil {
   public static function serverDomain() {
      static $domain; 
      if(!isset($domain)) {
         $domain = OC_Request::serverHost(); 
         if(!isDevMode() && !isTestMode()) {
            // take out subdomain/www
            $domain = preg_replace("/^(.*\.)?([^.]*\..*)$/", "$2", $domain);
         }
         else if(isTestMode()) {
            $domain = str_replace("www.", "", $domain); 
         }
      }

      return $domain; 
   }

   public static function replaceOCPrefix($sql) {
      $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
      return str_replace( '*PREFIX*', $prefix, $sql );
   }

   public static function needSSL() {
      $config = PFactory::getConfig(); 
      if($config->get('ssl_mode') && OC_Request::serverProtocol() != 'https')
         return true; 

      return false; 
   }

   public static function isSSL() {
      return OC_Request::serverProtocol() == 'https'; 
   }

   /**
    * Make $url absolute based on ssl status. If ssl is not enabled, return http:: protocol only
    * This function is only needed if the page is required to enter ssl mode 
    *
    */ 
   public static function getAbsoluteSSLURL($url) {
      if(self::needSSL())
         return 'https://' . self::serverDomain() . $url; 
      else 
         return $url;
   }

   public static function unloadOCCss($cssfiles, $indexpage=false) {

      // remove out certain owncloud css styles
      $cssfiles = array_diff($cssfiles, array("/core/css/jquery-tipsy.css",
                                              "/core/css/styles.css",
                                              "/core/css/share.css",
                                              "/core/css/multiselect.css",
                                              "/remote.php/core.css", 
                                              "/core/css/jquery-ui-1.10.0.custom.css"
                                             ));
      if($indexpage) {
         $cssfiles = array_diff($cssfiles, array("/themes/jobs/core/css/multiselect.css"));
      }

      if(isDevMode())
         return $cssfiles; 

      return array_diff($cssfiles, array("/themes/jobs/core/css/multiselect.css"));
      
   }

   public static function unloadOCJs($jsfiles, $indexpage=false) {
      $jsfiles = array_diff($jsfiles, array("/core/js/jquery-1.7.2.min.js",
                                            "/core/js/jquery-ui-1.10.0.custom.js",
                                            "/core/js/jquery-showpassword.js",
                                            "/core/js/jquery-tipsy.js",
                                            "/core/js/share.js",
                                            "/core/js/config.js",
                                            "/core/js/router.js",
                                            "/core/js/oc-dialogs.js", 
                                            "/core/js/jquery.infieldlabel.js", 
                                            "/index.php/core/js/config.js", 
                                            "/remote.php/core.js", 
                                            "/search/js/result.js",
                                            "/apps/files_versions/js/versions.js",
                                            "/apps/files_sharing/js/share.js"
                                           ));


      if(isDevMode()) {
         $jsfiles = array_unique(array_merge(array("/themes/jobs/core/js/js.js", 
                                      "/core/js/compatibility.js", 
                                      "/core/js/eventsource.js", 
                                      "/core/js/oc-requesttoken.js", 
                                      "/core/js/visitortimezone.js"
                                 ), $jsfiles));

         return $jsfiles; 
      }

      // production mode, remove all un-optimized js
      $jsfiles = array_diff($jsfiles, array("/core/js/compatibility.js",
                                            "/themes/jobs/core/js/js.js",
                                            "/themes/jobs/core/js/multiselect.js", 
                                            "/core/js/eventsource.js",
                                            "/core/js/oc-requesttoken.js",
                                            "/core/js/backgroundjobs.js",
                                            "/core/js/visitortimezone.js"
                                           ));

      return $jsfiles;
   }

   public static function loadCss($src, $type = 'text/css', $media="screen") {
      $config = PFactory::getConfig();
      $release_datetime = $config->get('release_datetime', 0);
      $release_datetime = $release_datetime ? '.'.$release_datetime : '';
      $uri = "";
      if(!isDevMode()) {
         $src = preg_replace("/^[\/]?static/", "", $src);
         if(self::isSSL())
            $uri = OC_Request::serverProtocol(). '://ssl.'  . self::serverDomain() . "/static"; 
         else 
            $uri = OC_Request::serverProtocol(). '://static.'  . self::serverDomain(); 
      }

      echo '<link rel="stylesheet" href="'. $uri.$src.$release_datetime.'" type="'.$type.'" media="'.$media.'" />'; 
   }

   public static function loadJs($src) {
      $config = PFactory::getConfig();
      $release_datetime = $config->get('release_datetime', 0);
      $release_datetime = $release_datetime ? '.'.$release_datetime : '';
      $uri = ""; 
      if(!isDevMode()) {
         $src = preg_replace("/^[\/]?static/", "", $src);
         if(self::isSSL())
            $uri = OC_Request::serverProtocol(). '://ssl.'  . self::serverDomain() . "/static"; 
         else 
            $uri = OC_Request::serverProtocol(). '://static.'  . self::serverDomain(); 
      }

      echo '<script type="text/javascript" src="' . $uri . $src . $release_datetime . '"></script>';
   }

   public static function getImageUrl($src) {
      $uri = "";
      if(!isDevMode()) {
         $src = preg_replace("/^[\/]?images/", "", $src);
         $uri = OC_Request::serverProtocol(). '://images.'  . self::serverDomain();
      }

      return $uri . $src;
   }

   public static function checkUserLogin($company = false, $return=null) {
      if(OC_User::isLoggedIn())
         return true;
      $app = PFactory::getApplication();
      if (empty($return)) {
         $return = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : PFactory::getURI()."";
      }
      $app->setUserState("return", $return);

      if(isAjaxMode()) {
         return '<div id="loginrequired" ></div>';
      }

      if (!$company) {
         OC_Response::redirect(OC_Helper::linkToRoute('jobseeker_login'));
      } else {
         OC_Response::redirect(OC_Helper::linkToRoute('company_login'));
      }

      return false;
   }

   public static function saveDatedData($companyid, $folder) {
      // we don't proceed if folder doesn't exist or datadated folder doesn't exist 
      if(!$folder || !file_exists($folder) || !is_dir(OC::$SERVERROOT."/data/datadated/")) 
         return; 

      // check if it's file. if it's a file, we need to find the folder
      $p = $folder;
      if(is_file($folder)) {
         $folder = dirname($folder);
         $p = $folder; 
      }
      
      $subfolder = ''; 
      // need to check if the given folder belongs to this company 
      while(true) {
         if(basename($p) == $companyid)
            break; 

         $p = dirname($p); 

         // end of path ? 
         if($p == '/')
            break; 
      }

      // final check. if it doesn't match, return 
      if(basename($p) != $companyid)
         return; 

      // $p should be /var/www/pipahr/cloud/data/<userdir>/company/$companyid 
      // $subfolder is /var/www/pipahr/cloud/data/<userdir> 
      $subfolder = str_replace(dirname(dirname($p)), '', $folder); 
      
      $config = PFactory::getConfig();
      $date = PFactory::getDate(time(), $config->get("offset"))->format("Y-m-d"); 
      // $path is: /var/www/pipahr/cloud/data/datadated/2014-01-01/1000000/
      $path = OC::$SERVERROOT."/data/datadated/" . $date . "/" . $subfolder; 

      mkdir_recursive($path); 

      # copy all content in this folder over to dated folder 
      exec("/bin/cp -f $folder/* $path/"); 

   }
}
